package secondriver.qiniucs.client;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ImageView;

public class MainActivity extends Activity {

	public static final int CHOOSE_IMAGE_CODE = 1;

	private ImageView imageView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		imageView = (ImageView) findViewById(R.id.imageView);
		registerForContextMenu(imageView);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.add(0, 0, 0, "选择文件");
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (item.getItemId() == 0) {
			Intent intent = new Intent(
					Intent.ACTION_PICK,
					android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			this.startActivityForResult(intent, CHOOSE_IMAGE_CODE);
			return true;
		}
		return super.onContextItemSelected(item);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CHOOSE_IMAGE_CODE && requestCode == RESULT_OK
				&& null != data) {
			Uri uri = data.getData();
			Cursor cursor = getContentResolver().query(uri,
					new String[] { MediaStore.Images.Media.DATA }, null, null,
					null);
			if (cursor.moveToFirst()) {
				int columnIndex = cursor
						.getColumnIndex(MediaStore.Images.Media.DATA);
				String pathName = cursor.getString(columnIndex);
				cursor.close();
				imageView.setImageBitmap(this.getBitmap(pathName));
			}
		}
	}

	private Bitmap getBitmap(String pathName) {
		return BitmapFactory.decodeFile(pathName);
	}
}
